#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QDir>
#include <QFileInfoList>
#include <QCamera>
#include <QCameraInfo>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QMessageBox>
#include <QPixmap>
#include <QDateTime>
#include <QUrlQuery>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>

const QString baiduTokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%1&client_secret=%2";
const char *client_id = "nIoNprkXkaGJhhhn7R9wmuN7";
const char *secret_id = "EUWLeqPI7GrAtqAtV4U8TlbbdyvEn5ME";
const QString baiduimgurl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=%1";

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 获取摄像头设备
    QList<QCameraInfo> infos = QCameraInfo::availableCameras();
    QString camera = infos.value(0).deviceName();

    // 打开摄像头
    ca = new QCamera(camera.toUtf8(), this);
    ui->camera->show();

    QCameraViewfinder *v2 = new QCameraViewfinder(ui->camera);
    v2->resize(ui->camera->size());
    ca->setViewfinder(v2);
    v2->show();
    ca->start();

    // 初始化摄像头截图对象
    capture = new QCameraImageCapture(ca);
    connect(capture, &QCameraImageCapture::imageCaptured, this, &MainWindow::onImageCaptured);

    savePath = "D:/QianRuShi/24081/QT/QT/Piece/Tu";
    if (!savePath.endsWith("/")) {
        savePath += "/";
    }

    // 创建定时器，用于定时截图
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::captureAndOpenImage);
    timer->start(5000);  // 5秒触发一次
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::captureAndOpenImage()
{
    // 截取图片
    QString fileName = QDateTime::currentDateTime().toString("yyyyMMddHHmmss") + ".jpg";
    capture->capture(savePath + fileName);
}

void MainWindow::onImageCaptured(int id, const QImage &image)
{
    // 保存截图到文件
    QString fileName = QDateTime::currentDateTime().toString("yyyyMMddHHmmss") + ".jpg";
    image.save(savePath + fileName);

    // 显示截图
    QPixmap pix(savePath + fileName);
    ui->label->setPixmap(pix.scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));

    // 自动识别最新图片
    recognizeImage(fileName);

    // 检查文件夹中的图片数量，如果超过20张，删除最旧的10张
    deleteOldImages();
}

void MainWindow::recognizeImage(const QString &fileName)
{
    QByteArray img = Image::imageToBase64(savePath + fileName);
    if (img.isEmpty())
    {
        QMessageBox::warning(this, "提示", "图片转换失败");
        return;
    }

    // 构建请求体
    QUrlQuery query;
    query.addQueryItem("image", img);
    query.addQueryItem("language_type", "CHN_ENG");  // 中英文混合
    query.addQueryItem("detect_direction", "true");  // 检测旋转
    QByteArray imgData = query.toString(QUrl::FullyEncoded).toUtf8();

    // 获取 access_token
    QByteArray replayData;  // 保存回复信息
    QString url = QString(baiduTokenUrl).arg(client_id).arg(secret_id);
    QMap<QString, QString> header;  // 封装头部信息
    header.insert("Content-Type", "application/x-www-form-urlencoded");
    QString accessToken;

    bool result = Http::post_sync(url, header, imgData, replayData);
    if (result)
    {
        QJsonObject obj = QJsonDocument::fromJson(replayData).object();
        accessToken = obj.value("access_token").toString();
        qDebug() << "Access Token:" << accessToken;
        qDebug() << "Token Response:" << replayData;
    }
    else
    {
        QMessageBox::warning(this, "提示", "获取 access_token 失败");
        return;
    }

    replayData.clear();
    QString imgurl = baiduimgurl.arg(accessToken);
    qDebug() << "Image Recognition URL:" << imgurl;
    result = Http::post_sync(imgurl, header, imgData, replayData);
    qDebug() << "Image Recognition Response:" << replayData;
    if (result)
    {
        QJsonObject obj = QJsonDocument::fromJson(replayData).object();
        qDebug() << "Response Object:" << obj;
        if (obj.contains("error_code") && obj.value("error_code").toInt() != 0)
        {
            QString errorMsg = obj.value("error_msg").toString();
            QMessageBox::warning(this, "提示", "图像识别失败: " + errorMsg);
            return;
        }

        QJsonValue val = obj.value("words_result");
        if (val.isArray())
        {
            QStringList wordsList;
            QJsonArray wordsArray = val.toArray();
            for (const QJsonValue &wordValue : wordsArray)
            {
                if (wordValue.isObject())
                {
                    QString word = wordValue.toObject().value("words").toString();
                    wordsList.append(word);
                }
            }
            QString recognizedText = wordsList.join(""); // 连接成一个字符串
            qDebug() << "Recognized Text:" << recognizedText;
            ui->lineEdit->setText(recognizedText);
            storeAndDisplayRecognizedText(recognizedText); // 调用新的存储和显示函数
            return;
        }
    }

    ui->lineEdit->setText("unknown");
}

void MainWindow::deleteOldImages()
{
    QDir dir(savePath);
    QFileInfoList fileList = dir.entryInfoList(QDir::Files, QDir::Time);

    if (fileList.size() > 20)
    {
        // 删除最旧的10张图片
        for (int i = 0; i < 10; ++i)
        {
            if (i < fileList.size())
            {
                QFile::remove(fileList.last().absoluteFilePath());
                fileList.removeLast();
            }
        }
    }
}

void MainWindow::storeAndDisplayRecognizedText(const QString &text)
{
    if (text.length() == 9)
    {
        for (int i = 0; i < 9; ++i)
        {
            QChar currentChar = text.at(i);
            int row = i / 3;
            int col = i % 3;

            if (currentChar == '0' || currentChar == 'o' || currentChar == 'O')
            {
                recognizedChars[row][col] = '2';
            }
            else if (currentChar == 'x' || currentChar == 'X')
            {
                recognizedChars[row][col] = '1';
            }
            else
            {
                recognizedChars[row][col] = '0';
            }
        }

        qDebug() << "Recognized Characters (3x3 Array):";
        for (int i = 0; i < 3; ++i)
        {
            QString rowString;
            for (int j = 0; j < 3; ++j)
            {
                rowString += recognizedChars[i][j];
                rowString += " ";
            }
            qDebug() << rowString;
        }
    }
    else
    {
        qDebug() << "Warning: Recognized text length is not 9. Text: " << text;
    }
}
